package ytr.android.sparrow;

import java.util.ArrayList;
import java.util.List;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * <pre>
 * 参加ユーザ名設定画面。
 * アプリ起動初回画面
 * </pre>
 * @author toki
 *
 */
public class UserSettingActivity extends SparrowBaseActivity {

	/**
	 * リスト制御用オブジェクト
	 */
	private ListView mListView;

	/**
	 * 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.user_setting);
		getViewControl();
		setViewStyle();
		setListItem();
		setListener();
	}

	private void getViewControl() {    	
		mListView = (ListView) findViewById(R.id.userList);
	}

	private void setViewStyle() {
		mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	}

	private void setListItem() {

		List<UserSettingItem> items = new ArrayList<UserSettingItem>();

		SparrowDBHelpter dbHelper = new SparrowDBHelpter(this);
		List<UserSettingItem> userName = dbHelper.getUserNameTableData();
		for (int i=0 ; i < userName.size() ; i++) {
			items.add(new UserSettingItem(userName.get(i).getResourceID(), userName.get(i).getName(), userName.get(i).getDataBaseID()));
		}

		ListAdapter adapter = new UserSettingActivityAdapter(this, R.layout.user_setting_row, items);
		mListView.setAdapter(adapter);
	}

	private void setListener() {

		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			/**
			 * AlertDialogのEditText操作用オブジェクト
			 */
			 private EditText dialogEditText;

			/**
			 * AlertDialogへListView変更位置通知用
			 */
			 private int activePosition;

			 @Override
			 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				 activePosition = position;

				 TextView listTextView = (TextView) view.findViewById(R.id.userNameText);
				 ImageView listImageView = (ImageView) view.findViewById(R.id.userIconView);

				 LayoutInflater inflater = LayoutInflater.from(UserSettingActivity.this);
				 View dialogView = inflater.inflate(R.layout.user_setting_dlalog, null);
				 dialogEditText = (EditText) dialogView.findViewById(R.id.userNameEdit);
				 dialogEditText.setText(listTextView.getText());

				 new AlertDialog.Builder(UserSettingActivity.this)
				 .setTitle(R.string.DiglogTitle_User_Name_Edit)
				 .setIcon(listImageView.getDrawable())
				 .setView(dialogView)
				 .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {

					 @Override
					 public void onClick(DialogInterface dialog, int which) {

						 ArrayAdapter<UserSettingItem> adapter = (ArrayAdapter<UserSettingItem>) mListView.getAdapter();
						 UserSettingItem updateObj = (UserSettingItem) mListView.getItemAtPosition(activePosition);
						 UserSettingItem removeObj = updateObj;
						 updateObj.setName(dialogEditText.getText().toString());
						 adapter.remove(removeObj);
						 adapter.insert(updateObj, activePosition);

						 adapter.notifyDataSetChanged();

					 }
				 }).show();
			 }
		});
	}

	/**
	 * 
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu_setting, menu);    	
		return true;
	}

	/**
	 * 
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.confirm_button :
			saveUserName();
			moveNextActivity();
			break;
		default:
			Log.w(getCommonLogTag(), "onOptionsItemSelected Unknown Resource ID");
		}
		return true;
	}

	private void moveNextActivity() {

		SharedPreferences pref = getSharedPreferences(getString(R.string.app_name), MODE_WORLD_READABLE);
		boolean ret = pref.getBoolean(InitSettingActivity.PREF_KEY_INIT_SETTING, InitSettingActivity.NOT_CONFIGURED);
		if(ret == InitSettingActivity.CONFIGURED) {
			startScoreManagementActivity();
		} else {
			startInitSettingActivity();
		}
	}

	private List<String> saveUserName() {

		List<UserSettingItem> newUserName = new ArrayList<UserSettingItem>();

		/*
		 * DBと正しく紐付けするため、DBから取得したID情報とListViewにセットしたIDを情報をマッチングしている
		 */
		SparrowDBHelpter dbHelper = new SparrowDBHelpter(this);
		List<UserSettingItem> userName = dbHelper.getUserNameTableData();
		for (int i=0 ; i < userName.size() ; i++) {
			View viewListRow = mListView.findViewWithTag(userName.get(i).getDataBaseID());
			TextView textView = (TextView) viewListRow.findViewById(R.id.userNameText);
			UserSettingItem tmp = new UserSettingItem(0, textView.getText().toString(), userName.get(i).getDataBaseID());
			newUserName.add(tmp);
		}

		dbHelper.setUserName(newUserName);

		return null;
	}


}